package com.example.canteen.exeception;

import com.example.canteen.util.Anonymous;
import com.example.canteen.util.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Api(tags = "文件上传(0304高凯)")
@Anonymous
@RestController
@RequestMapping("/api/file")
public class FileController {

    @Value("D:/ruoyi/uploadPath")
    private String UPLOAD_FOLDER;
    @ApiOperation(value = "文件上传",notes = "本地文件上传到服务器")
    @PostMapping("/upload")
    public AjaxResult upload(@RequestPart("file") MultipartFile file)  {
        if (file.isEmpty()){
            return AjaxResult.error("文件不能为空");
        }
        String fileName = file.getOriginalFilename();
        File path = new File(UPLOAD_FOLDER);
        if (!path.exists()){
            path.mkdirs();
        }
        File dest = new File(UPLOAD_FOLDER +"/"+ fileName);
        try {
            file.transferTo(dest);
            String url = "/private/" + fileName;
            return AjaxResult.success("上传成功").put("url",url);
        }catch (IOException e)
        {
            throw  new BizException(500,"上传失败");
        }
    }
}

